package com.cyan.app.workflow.activity.LGS;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.activity.SFC.GdlkCkActivity;
import com.cyan.app.workflow.activity.SFC.ItnbrBatActivity;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.CommonBean;
import com.cyan.app.workflow.bean.DelPoolListBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.json.JSONObject;

/**
 * Created by DXW on 2017-07-18.
 */

public class DellzlActivity extends BaseActivity {
    private TextView mTitleName;
    private Button mTitleSeach;
    private View mTitleView;
    private EditText mEditTextUser;
    private Button mButtonUser;
    private Button mButtonSubmit;
    private EditText mEditTextWahqy2;
    private EditText mEditTextWahqy1;
    private EditText mEditTextAdqy1;
    private EditText mEditTextAdqy2;
    private EditText mEditTextBadqy1;
    private EditText mEditTextBadqy2;
    private EditText mEditTextOkqy1;
    private EditText mEditTextOkqy2;
    private EditText mEditTextVarnr;
    private EditText mEditTextFixnr;
    private TextView mTextViewWahqy2_U;
    private TextView mTextViewWahqy1_U;
    private View lineWahqy2;
    private View lineOkqy2;
    private View lineBadqy1;
    private View lineBadqy2;
    private View lineAdqy2;
    private DelPoolListBean.DelpoolBean delpoolBean;
    private static final String USERNO = "DEL_LZL_USERNO";
    private ShowTipDialog showdialog = new ShowTipDialog();
    private boolean isUrmsr2=false;
    private LinearLayout mBat;
    private EditText mEditTextCk;
    private static final String WAREH = "del_lzl_wareh";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lgs_del_lzl);
        delpoolBean = (DelPoolListBean.DelpoolBean) getIntent().getSerializableExtra("delpoolDetail");
        titleBar();
        initView();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
            }
            if (!result.contains("40010")) {
                AppUtils.showTip(DellzlActivity.this, "员工不存在");
            }else {
                String pisUser = result.substring(5);;
                mEditTextUser.setText(pisUser);
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(USERNO,pisUser).commit();
            }
        }
        if(requestCode == 0x0001 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
            }
            if (!result.contains("30010")) {
                AppUtils.showTip(DellzlActivity.this, "库位不存在");
            }else{
                mEditTextFixnr.setText(String.valueOf(result.substring(5)));
            }
        }

        if(requestCode == 0x0003 && resultCode == RESULT_OK) {
            Intent intent = new Intent();
            intent.putExtra("poolno",delpoolBean.getPoolno());
            DellzlActivity.this.setResult(RESULT_OK,intent);
            finish();
        }
        if(requestCode == 0x0004 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("wareh");
                mEditTextCk.setText(String.valueOf(result));
                //PreferenceManager.getDefaultSharedPreferences(this).edit().putString(WAREH,result).commit();
            }
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //MobclickAgent.onPause(this);
        //MobclickAgent.onPageEnd("DDActivity");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //MobclickAgent.onResume(this);
        //MobclickAgent.onPageStart("DDActivity");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //DDDataFetcher.getInstance().unRegistPoolsObserver(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void titleBar() {
        mTitleName = (TextView) findViewById(R.id.top_title_info);
        mTitleName.setText("入库");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        if(delpoolBean.getIsqc()==1&&delpoolBean.getStatus()!=81) {
            mTitleSeach = (Button) findViewById(R.id.top_title_refres_with_icon);
            mTitleSeach.setVisibility(View.INVISIBLE);
            mTitleSeach = (Button) findViewById(R.id.top_title_refres);
            mTitleSeach.setVisibility(View.VISIBLE);
            mTitleSeach.setText("再送检");
            mTitleSeach.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("delpoolDetail", delpoolBean);
                    Intent intent = new Intent();
                    intent.setClass(DellzlActivity.this, DellzsActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 0x0003);
                }
            });
        }
        mTitleView = (View) findViewById(R.id.layout_main_ui_top2_title);
    }

    private void initView() {
        mEditTextCk= (EditText)findViewById(R.id.lgs_del_lzl_wareh);
        mEditTextCk.setInputType(InputType.TYPE_NULL);
        //String wareh = PreferenceManager.getDefaultSharedPreferences(this).getString(WAREH,null);
        //if(wareh!=null){
        //    mEditTextCk.setText(String.valueOf(wareh));
       // }
        String result ="W-" + delpoolBean.getItnbr().substring(0,1);
        mEditTextCk.setText(result);
        Button mButtonCk =(Button)findViewById(R.id.lgs_del_lzl_wareh_sm);
        mButtonCk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(DellzlActivity.this, GdlkCkActivity.class);
                startActivityForResult(intent, 0x0004);
            }
        });
        View resultView =  findViewById(R.id.lgs_del_lzl_result_lay);
        if(delpoolBean.getIsqc()==1) {
            TextView mEditTextQc = (TextView) findViewById(R.id.lgs_del_lzl_chqy);
            mEditTextQc.setText("送检 " + delpoolBean.getAccqty().toString());

            TextView mEditTextOk = (TextView) findViewById(R.id.lgs_del_lzl_okqy);
            mEditTextOk.setText("良品 " +  delpoolBean.getOkqty());

            TextView mEditTextNg = (TextView) findViewById(R.id.lgs_del_lzl_ngqy);
            mEditTextNg.setText("不良 " + delpoolBean.getNgqty().toString());

            TextView mEditTextBad = (TextView) findViewById(R.id.lgs_del_lzl_badqy);
            mEditTextBad.setText("报废 " + delpoolBean.getBadqty().toString());

            TextView mEditTextBck = (TextView) findViewById(R.id.lgs_del_lzl_bckqy);
            mEditTextBck.setText("退回 " + delpoolBean.getBckqy1().toString());
        }else {
            resultView.setVisibility(View.GONE);
            delpoolBean.setOkqty(delpoolBean.getAccqy1());
        }
        //已流数
        mEditTextWahqy1 = (EditText)findViewById(R.id.lgs_del_lzl_wahqy1);
        mEditTextWahqy1.setText(String.valueOf(delpoolBean.getWahqy()));
        mEditTextWahqy1.setInputType(InputType.TYPE_NULL);
        mTextViewWahqy1_U = (TextView) findViewById(R.id.lgs_del_lzl_wahqy1_u);
        mTextViewWahqy1_U.setText(delpoolBean.getUnmsr1());
        //良品
        mEditTextOkqy1 = (EditText)findViewById(R.id.lgs_del_lzl_okqy1);
        mEditTextOkqy1.setText(String.valueOf(delpoolBean.getChqy1()-delpoolBean.getWahqy()-delpoolBean.getBckqy1()));
        mEditTextOkqy1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(isUrmsr2&& s.length()>0&&AppUtils.isNumeric(s.toString())){
                    Double okqy22 = 0.0;
                    Double okqy11=Double.parseDouble(s.toString());
                    Double okqy1=delpoolBean.getChqy1()-delpoolBean.getWahqy()-delpoolBean.getBckqy1();
                    Double okqy2=delpoolBean.getChqy2()-delpoolBean.getWahqy2()-delpoolBean.getBckqy2();
                    if(okqy11==okqy1){
                        okqy22 =okqy2;
                    }else if(okqy1>0&&okqy2>0){
                        okqy22 =Math.round((okqy2/okqy1)*okqy11*100)*0.01d;
                    }
                    mEditTextOkqy2.setText(okqy22.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //报废数
        mEditTextBadqy1 = (EditText)findViewById(R.id.lgs_del_lzl_badqy1);
        mEditTextBadqy1.setText("0");
        //赠送
        mEditTextAdqy1 = (EditText)findViewById(R.id.lgs_del_lzl_adqy1);
        mEditTextAdqy1.setText("0");
        //批次库位
        mEditTextVarnr= (EditText)findViewById(R.id.lgs_del_lzl_varnr);
        mEditTextVarnr.setText(AppUtils.getDateString());
        mEditTextFixnr= (EditText)findViewById(R.id.lgs_del_lzl_fixnr);
        //mEditTextFixnr.setText("A");
            mEditTextWahqy2 = (EditText)findViewById(R.id.lgs_del_lzl_wahqy2);
            mEditTextWahqy2.setText(String.valueOf(delpoolBean.getWahqy2()));
            mEditTextWahqy2.setInputType(InputType.TYPE_NULL);
            mTextViewWahqy2_U = (TextView) findViewById(R.id.lgs_del_lzl_wahqy2_u);
            mTextViewWahqy2_U.setText(delpoolBean.getUnmsr2());
            mEditTextOkqy2 = (EditText)findViewById(R.id.lgs_del_lzl_okqy2);
            mEditTextOkqy2.setText(String.valueOf(delpoolBean.getChqy2()-delpoolBean.getWahqy2()-delpoolBean.getBckqy2()));
            mEditTextBadqy2 = (EditText)findViewById(R.id.lgs_del_lzl_badqy2);
            mEditTextBadqy2.setText("0");
            mEditTextAdqy2 = (EditText)findViewById(R.id.lgs_del_lzl_adqy2);
            mEditTextAdqy2.setText("0");
        if(delpoolBean.getDeltype()==0&&delpoolBean.getUnmsr2() != null && delpoolBean.getUnmsr2().length()>0){
            isUrmsr2 = true;
        }else{
            lineWahqy2=(View) findViewById(R.id.lgs_del_lzl_line_wahqy2);
            lineWahqy2.setVisibility(View.GONE);
            lineOkqy2=(View) findViewById(R.id.lgs_del_lzl_line_okqy2);
            lineOkqy2.setVisibility(View.GONE);
            lineBadqy2=(View) findViewById(R.id.lgs_del_lzl_line_badqy2);
            lineBadqy2.setVisibility(View.GONE);
            lineAdqy2=(View) findViewById(R.id.lgs_del_lzl_line_adqy2);
            lineAdqy2.setVisibility(View.GONE);
        }
        if(delpoolBean.getDeltype()==0){

            lineBadqy1=(View) findViewById(R.id.lgs_del_lzl_line_badqy1);
            lineBadqy1.setVisibility(View.GONE);
            lineBadqy2=(View) findViewById(R.id.lgs_del_lzl_line_badqy2);
            lineBadqy2.setVisibility(View.GONE);
        }else {
            mEditTextOkqy1.setInputType(InputType.TYPE_CLASS_NUMBER);
            mEditTextAdqy1.setInputType(InputType.TYPE_CLASS_NUMBER);
        }
        Button mButtonFixnr =(Button)findViewById(R.id.lgs_del_lzl_fixnr_sm);
        mButtonFixnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DellzlActivity.this, CaptureActivity.class), 0x0001);
            }
        });

        mBat = (LinearLayout)findViewById(R.id.lgs_del_lzl_fixnr_bat);
        mBat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("GdlzLkItnbr",delpoolBean.getItnbr());
                intent.setClass(DellzlActivity.this,ItnbrBatActivity.class);
                startActivity(intent);
            }
        });
        mEditTextUser=(EditText)findViewById(R.id.lgs_del_lzl_user);
        mEditTextUser.setInputType(InputType.TYPE_NULL);
        //mEditTextUser.setText("1019");
        String ygbh = PreferenceManager.getDefaultSharedPreferences(this).getString(USERNO,null);
        if(ygbh!=null){
            mEditTextUser.setText(String.valueOf(ygbh));
        }
        mButtonUser =(Button)findViewById(R.id.lgs_del_lzl_user_sm);
        mButtonUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DellzlActivity.this, CaptureActivity.class), 0x0002);
            }
        });
        mButtonSubmit = (Button)findViewById(R.id.lgs_del_lzl_submit);
        mButtonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(delpoolBean.getDeltype()==1){//外协
                    if (mEditTextOkqy1.getText().length() == 0||Double.parseDouble(mEditTextOkqy1.getText().toString())< 0) {
                        AppUtils.showTip(DellzlActivity.this, "良品数量1必须大于等于0");
                        return;
                    }
                    if (mEditTextBadqy1.getText().length() == 0||Double.parseDouble(mEditTextBadqy1.getText().toString())< 0) {
                        AppUtils.showTip(DellzlActivity.this, "报废数量1必须大于等于0");
                        return;
                    }
                    if (mEditTextAdqy1.getText().length() == 0||Double.parseDouble(mEditTextAdqy1.getText().toString())< 0) {
                        AppUtils.showTip(DellzlActivity.this, "报废数量1必须大于等于0");
                        return;
                    }
                    if ((Double.parseDouble(mEditTextBadqy1.getText().toString())+Double.parseDouble(mEditTextOkqy1.getText().toString()))<=0) {
                        AppUtils.showTip(DellzlActivity.this, "良品数+报废数之和必须大于0");
                        return;
                    }
                    if (Double.parseDouble(mEditTextBadqy1.getText().toString())>0&&delpoolBean.getBadqty()<= 0) {
                        AppUtils.showTip(DellzlActivity.this, "质检结果无报废，不能报废");
                        return;
                    }
                    if (Double.parseDouble(mEditTextOkqy1.getText().toString()) + Double.parseDouble(mEditTextBadqy1.getText().toString())>delpoolBean.getChqy1()-delpoolBean.getBckqy1()-delpoolBean.getWahqy()) {
                        AppUtils.showTip(DellzlActivity.this, "流转数量不能大于待处理数，待处理数=点收数-已流转数-已退回数");
                        return;
                    }
                    if (mEditTextAdqy1.getText().length() == 0||Double.parseDouble(mEditTextAdqy1.getText().toString())< 0) {
                        AppUtils.showTip(DellzlActivity.this, "赠送数量1必须大于等于0");
                        return;
                    }
                }else{ //采购
                    if (mEditTextOkqy1.getText().length() == 0||Double.parseDouble(mEditTextOkqy1.getText().toString())<= 0) {
                        AppUtils.showTip(DellzlActivity.this, "良品数量1必须大于0");
                        return;
                    }
                    if (Double.parseDouble(mEditTextOkqy1.getText().toString())>delpoolBean.getChqy1()-delpoolBean.getBckqy1()-delpoolBean.getWahqy()) {
                        AppUtils.showTip(DellzlActivity.this, "流转数量不能大于待处理数，待处理数=点收数-已流转数-已退回数");
                        return;
                    }
                    if (mEditTextAdqy1.getText().length() == 0||Double.parseDouble(mEditTextAdqy1.getText().toString())< 0) {
                        AppUtils.showTip(DellzlActivity.this, "赠送数量1必须大于等于0");
                        return;
                    }
                    if (isUrmsr2&&(mEditTextOkqy2.getText().length() == 0||Double.parseDouble(mEditTextOkqy2.getText().toString())<= 0)) {
                        AppUtils.showTip(DellzlActivity.this, "流转数量2必须大于0");
                        return;
                    }
                    if (isUrmsr2&&(Double.parseDouble(mEditTextOkqy2.getText().toString())>delpoolBean.getChqy2()-delpoolBean.getBckqy2()-delpoolBean.getWahqy2())) {
                        AppUtils.showTip(DellzlActivity.this, "流转数量2不能大于待处理数2，待处理数2=点收数2-已流转数2-已退回数2");
                        return;
                    }
                    if (mEditTextAdqy1.getText().length() == 0||Double.parseDouble(mEditTextAdqy1.getText().toString())< 0) {
                        AppUtils.showTip(DellzlActivity.this, "赠送数量1必须大于等于0");
                        return;
                    }
                    if (isUrmsr2&&(mEditTextAdqy2.getText().length() == 0||Double.parseDouble(mEditTextAdqy2.getText().toString())< 0)) {
                        AppUtils.showTip(DellzlActivity.this, "赠送数量2必须大于等于0");
                        return;
                    }
                    if (isUrmsr2&&Double.parseDouble(mEditTextAdqy1.getText().toString())> 0&&Double.parseDouble(mEditTextAdqy2.getText().toString())<= 0) {
                        AppUtils.showTip(DellzlActivity.this, "赠送数量2必须大于0");
                        return;
                    }
                    if(isUrmsr2&&(Double.parseDouble(mEditTextOkqy1.getText().toString())==delpoolBean.getChqy1()-delpoolBean.getBckqy1()-delpoolBean.getWahqy()) && (Double.parseDouble(mEditTextOkqy2.getText().toString())!=delpoolBean.getChqy2()-delpoolBean.getBckqy2()-delpoolBean.getWahqy2())){
                        AppUtils.showTip(DellzlActivity.this, "数量1剩余数量为0时，数量2剩余数量也必须为0");
                        return;
                    }
                    if(isUrmsr2&&(Double.parseDouble(mEditTextOkqy1.getText().toString())!=delpoolBean.getChqy1()-delpoolBean.getBckqy1()-delpoolBean.getWahqy()) && (Double.parseDouble(mEditTextOkqy2.getText().toString())==delpoolBean.getChqy2()-delpoolBean.getBckqy2()-delpoolBean.getWahqy2())){
                        AppUtils.showTip(DellzlActivity.this, "数量2剩余数量为0时，数量1剩余数量也必须为0");
                        return;
                    }
                }
                if (mEditTextCk.getText().toString().isEmpty()) {
                    AppUtils.showTip(DellzlActivity.this, "仓库不能为空");
                    return;
                }
                if (mEditTextUser.getText().toString().isEmpty()) {
                    AppUtils.showTip(DellzlActivity.this, "送检人员不能为空");
                     return;
                }
                if (mEditTextVarnr.getText().toString().isEmpty()) {
                    AppUtils.showTip(DellzlActivity.this, "批号不能为空");
                    return;
                }
                if (mEditTextFixnr.getText().toString().isEmpty()) {
                    AppUtils.showTip(DellzlActivity.this, "库位不能为空");
                    return;
                }
                new submitAsyncLoader().execute(mEditTextVarnr.getText().toString()
                                                ,mEditTextFixnr.getText().toString()
                                                ,mEditTextUser.getText().toString()
                                                ,mEditTextOkqy1.getText().toString()
                                                ,mEditTextOkqy2.getText().toString()
                                                ,mEditTextBadqy1.getText().toString()
                                                ,mEditTextBadqy2.getText().toString()
                                                ,mEditTextAdqy1.getText().toString()
                                                ,mEditTextAdqy2.getText().toString()
                                                ,mEditTextCk.getText().toString()
                );
            }
        });
    }
    public class submitAsyncLoader extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            showdialog.showDialog(DellzlActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            String action ="510";//外协
            if(delpoolBean.getDeltype()==0){
                action ="512"; //采购
            }
            try{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("poolno", delpoolBean.getPoolno());
                jsonObject.put("varnr",params[0]);
                jsonObject.put("fixnr",params[1]);
                jsonObject.put("userno", params[2]);
                jsonObject.put("okqy1", params[3]);
                jsonObject.put("okqy2",params[4]);
                jsonObject.put("badqy1",params[5]);
                jsonObject.put("badqy2", params[6]);
                jsonObject.put("adqy1",params[7]);
                jsonObject.put("adqy2", params[8]);
                jsonObject.put("wareh", params[9]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, action, jsonObject.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s == null||s.isEmpty()||s.contains("html")) {
                AppUtils.showTip(DellzlActivity.this,"操作异常，请稍后再试！");
                showdialog.closeDialog();
                return;
            }
            CommonBean commonBean = new Gson().fromJson(s, CommonBean.class);
            if (commonBean.getCode()==1) {
                Intent intent = new Intent();
                intent.putExtra("poolno",delpoolBean.getPoolno());
                DellzlActivity.this.setResult(RESULT_OK,intent);
                AppUtils.showTip(DellzlActivity.this,"保存成功。");
                showdialog.closeDialog();
                finish();
            }else {
                DellzlActivity.this.setResult(RESULT_CANCELED);
                AppUtils.showTip(DellzlActivity.this,"保存失败，"+commonBean.getMsg());
                showdialog.closeDialog();
            }
        }

        @Override
        protected void onCancelled(String s) {
            DellzlActivity.this.setResult(RESULT_CANCELED);
        }
    }
}
